
import React from 'react';
import './retailPatterns.scss';
import SelectType from 'views/component/selectType';
import XDate from 'xdate';
import { ShopApi } from 'js/api/shop';
import echarts from 'js/lib/echarts';
import $ from 'jquery';
import { Link } from 'react-router';

const timeData = [{ id: 'day', name: '日' }, { id: 'month', name: '月' }, { id: 'season', name: '季' }, { id: 'year', name: '年' }];
let chartFontSize = parseInt(window.fontSize / 4);

const RetailPatternItem = React.createClass({
    componentDidMount() {
        this.setChart(this.props.data)
    },
    setChart(data) {

        let xAxisData = [],
            seriesData = [],
            timeType = this.props.timeType,
            startValue = 0,
            endValue = 5;

        for (let i in data) {
            if (timeType === 'day') {
                xAxisData.push(new XDate(data[i].CTIME).toString('MM-dd\nyyyy年'));
                seriesData.push(data[i].CDATA);
            } else if (timeType === 'month') {
                xAxisData.push(new XDate(data[i].CTIME).toString('M月\nyyyy年'));
                seriesData.push(data[i].CDATA);
            } else if (timeType === 'season') {
                let t = new Date(data[i].YEAR + ' ' + (parseInt(data[i].CTIME - 1) * 3 + 1));
                if (t <= new Date().getTime()) {
                    xAxisData.push('第' + data[i].CTIME + '季度\n' + data[i].YEAR + '年');
                    seriesData.push(data[i].CDATA);
                }
            } else if (timeType === 'year') {
                xAxisData.push(data[i].YEAR + '年');
                seriesData.push(data[i].CDATA);
            }
        }
        if (seriesData.length >= 5) {
            startValue = seriesData.length - 5;
            endValue = seriesData.length - 1;
        }
        let option = {
            textStyle: {
                fontSize: chartFontSize
            },
            animation: false,
            grid: {
                width: '90%',
                left: '5%',
                top: '12%',
                height: '72%'
            },
            xAxis: [{
                type: 'category',
                axisTick: {
                    show: false
                },
                axisLabel: {
                    show: true,
                    interval: 0,
                    textStyle: {
                        color: '#ccc',
                        fontSize: chartFontSize
                    }
                },
                splitLine: {
                    show: false
                },
                data: xAxisData
            }],
            yAxis: [{
                type: 'value',
                axisLine: {
                    show: false,
                    onZero: false
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: '#3f4147'
                    }
                },
                axisLabel: false
            }],
            dataZoom: {
                show: 'true',
                type: 'inside',
                startValue: startValue,
                endValue: endValue
            },
            series: [{
                type: 'line',
                smooth: true,
                lineStyle: {
                    normal: {
                        color: '#e6d784'
                    }
                },
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                        formatter: '{c}',
                        textStyle: {
                            color: '#ccc'
                        }
                    }
                },
                data: seriesData
            }]
        };
        this.chart = echarts.init(this.refs.chart);
        this.chart.setOption(option);
    },
    render() {
        return <div className="retailPatternItem">
            <div className="head flex">
                <div className="flex-col-1 flex-center"><i className="icon icon_pattern"></i></div>
                <div className="title">{this.props.data.name}</div>
                <div className="flex-col-3 text-center rank">名次:{this.props.rank}</div>
                <Link className="flex-g-1 text-right link" to={'retailPatternflowSummary/' + this.props.shopId + '/' + this.props.data[0].INDUSTRYID}>查看详情{'>'}</Link>
            </div>
            <div className="chart" ref='chart'></div>
        </div>
    }
});

const RetailPatterns = React.createClass({
    getInitialState() {
        return { TimeType: 'day', CurrDate: new XDate().toString('yyyy-MM-dd'), patternsData: [] }
    },
    componentDidMount() {
        this.getAllPatternsFlow();
    },
    getAllPatternsFlow() {
        let query = {
            ShopId: this.props.params.shopId,
            CurrDate: this.state.CurrDate,
            TimeType: this.state.TimeType,
            AreaTypeId: 8
        }
        ShopApi.getAllPatternsFlow(query, (data) => {
            this.setChart(data);
        })
    },
    setChart(data) {
        let self = this,
            patternData = {},
            len = 0,
            timeType = this.state.TimeType;
        for (let i in data) {
            let id = data[i].INDUSTRYID;
            if (!patternData[id]) {
                patternData[id] = [];
            }
            if (timeType === 'season') {
                let year = data[i].YEAR
                let seasonIndex = data[i].CTIME
                if (new Date(year + ' ' + ((parseInt(seasonIndex) - 1) * 3 + 1)).getTime() > new Date().getTime()) {
                    continue
                }
            }
            patternData[id].push(data[i])
        }
        for (let i in patternData) {
            len += 1;
        }
        console.log(patternData)
        if (len > 8) {
            self.setPatternsBarChart(patternData)
        } else {
            self.setPatternsPieChart(patternData);
        }
        this.setPatternData(patternData);
    },
    setPatternsPieChart(patternData) {
        let seriesData = [];
        for (let i in patternData) {
            if (parseInt(patternData[i][patternData[i].length - 1].CDATA) !== 0) {
                let d = {
                    value: patternData[i][patternData[i].length - 1].CDATA,
                    name: patternData[i][patternData[i].length - 1].INDUSTRYNAME
                }
                seriesData.push(d);
            }
        }
        if (seriesData.length <= 0) {
            $(this.refs.chart).html('空数据');
            return
        }
        let option = {
            textStyle: {
                fontSize: chartFontSize
            },
            animation: false,
            tooltip: {
                trigger: 'item',
                formatter: "{b}<br/>{c}人次({d}%)",
                backgroundColor: '#8591CD'
            },
            grid: {
                width: '80%'
            },
            color: [
                '#c74c63',
                '#fc8d20',
                '#a3c0a4',
                '#8b777a',
                '#aa9be0',
                '#a2dad9',
                '#51aef3',
                '#f18696',
                '#498680',
                '#32678d',
                '#51408f',
                '#ffe6af'
            ],
            series: [{
                type: 'pie',
                radius: [
                    '30%', '55%'
                ],
                label: {
                    normal: {
                        formatter: "{b}\n{d}%"
                    },
                },
                labelLine: {
                    normal: {
                        length: 20
                    }
                },
                data: seriesData
            }]
        };
        if (this.refs.chart) {
            this.patternsChart = echarts.init(this.refs.chart);
            this.patternsChart.setOption(option);
        }

    },
    setPatternsBarChart(patternData) {
        let self = this,
            seriesData1 = [],
            seriesData2 = [],
            total = 0,
            xAxisData = [],
            timeType = this.state.TimeType;
        for (let i in patternData) {
            let data = parseInt(patternData[i][patternData[i].length - 1].CDATA);
            seriesData1.push(data + '');
            xAxisData.push(patternData[i][patternData[i].length - 1].INDUSTRYNAME);
            total += data;
        }
        if (seriesData1.length <= 0) {
            $(this.refs.chart).html('空数据');
            return
        }
        let max = 0;
        for (let i in seriesData1) {
            if (parseInt(seriesData1[i]) === 0) {
                seriesData2.push('-');
                continue
            }
            let per = (parseInt(seriesData1[i]) / total * 100).toFixed(1);
            if (per > max) {
                max = parseInt(per) + 1;
            }
            seriesData2.push(per);
        }
        let option = {
            textStyle: {
                fontSize: chartFontSize
            },
            animation: false,
            color: ['#54A5E6'],
            tooltip: {
                trigger: 'axis',
                formatter: '人数: {c0}人次<br/>人次占比：{c1}%'
            },
            grid: {
                left: '10%',
                width: '80%'
            },
            xAxis: {
                splitLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    show: true,
                    interval: 0,
                    textStyle: {
                        color: '#9A9A9A',
                        fontSize: chartFontSize
                    }
                },
                data: xAxisData
            },
            yAxis: [{
                name: '单位：人次',
                nameTextStyle: {
                    color: '#A8A8A8'
                },
                axisLine: {
                    show: false,
                    onZero: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: false,
                type: 'value'
            }, {
                max: max * 2,
                min: 0,
                type: 'value',
                axisLine: {
                    show: false,
                    onZero: false
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                },
                axisLabel: false
            }],
            dataZoom: {
                type: 'inside',
                startValue: 0,
                endValue: 3
            },
            series: [{
                yAxisIndex: 0,
                type: 'bar',
                barWidth: 40,
                itemStyle: {
                    normal: {
                        label: {
                            show: true,
                            position: 'top'
                        }
                    }
                },
                data: seriesData1
            }, {
                yAxisIndex: 1,
                type: 'line',
                lineStyle: {
                    normal: {
                        color: '#7ED53D'
                    }
                },
                label: {
                    normal: {
                        show: true,
                        position: 'bottom',
                        formatter: '{c}%',
                        textStyle: {
                            color: '#E1EDF5'
                        }
                    }
                },
                data: seriesData2
            }]
        };
        if (this.refs.chart) {
            this.patternsChart = echarts.init(this.refs.chart);
            this.patternsChart.setOption(option);
        }
    },
    setPatternData(patternData) {
        let data = [];
        for (let i in patternData) {
            data.push({
                name: patternData[i][patternData[i].length - 1].INDUSTRYNAME,
                data: patternData[i],
                rankData: patternData[i].length > 0 ? parseInt(patternData[i][patternData[i].length - 1].CDATA) : 0,
                INDUSTRYID: patternData[i][patternData[i].length - 1].INDUSTRYID
            })
        }
        data.sort(function (a1, a2) {
            return a1.rankData < a2.rankData ? 1 : -1;
        });
        this.setState({ patternsData: data });
    },
    selectTypeOnChange(value) {
        this.state.TimeType = value;
        this.setState({ TimeType: value })
        this.getAllPatternsFlow();
    },
    render() {
        let RetailPatternsNode = this.state.patternsData.map((item, i) => {
            return <RetailPatternItem data={item.data} timeType={this.state.TimeType} rank={i + 1} shopId={this.props.params.shopId} />
        })
        return (
            <div id="retailPatterns" >
                <div className="flowContent">
                    <div className="flowHead">
                        <div className="title">业态客流量占比以及排名</div>
                    </div>
                    <div>
                        <SelectType data={timeData} value={this.state.TimeType} onChange={this.selectTypeOnChange} />
                    </div>
                    <div className="bottomTitle">业态客流占比图</div>
                    <div className="chart flex-center" ref='chart'></div>
                </div>
                {RetailPatternsNode}
            </div>
        );
    }
})

module.exports = RetailPatterns;